<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import request from '@/utils/request'
import { useDataIterator, IteratorFactory } from '@/utils/data-iterators'

// 响应式数据
const loading = ref(false)
const doctorsData = ref([])
const filters = reactive({
  department: null,
  minRating: 0,
  maxFee: 1000,
  specialties: []
})

// 分页状态
const pagination = reactive({
  currentPage: 1,
  pageSize: 6,
  total: 0
})

// 创建医生迭代器
let doctorIterator = null
let paginationIterator = null

// 计算属性 - 直接使用后端返回的已过滤数据
const filteredDoctors = computed(() => {
  const result = doctorsData.value || []
  console.log('🔍 filteredDoctors 计算结果:', result.length, result)
  return result
})

const paginatedDoctors = computed(() => {
  // 后端已经处理了分页，直接返回数据
  return {
    data: filteredDoctors.value,
    hasNext: pagination.currentPage * pagination.pageSize < pagination.total,
    hasPrev: pagination.currentPage > 1,
    page: pagination.currentPage,
    totalPages: Math.ceil(pagination.total / pagination.pageSize),
    totalItems: pagination.total
  }
})

// 获取医生数据
async function fetchDoctors() {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: pagination.currentPage,
      page_size: pagination.pageSize
    }
    
    // 添加过滤条件
    if (filters.department) {
      params.department_id = filters.department
    }
    if (filters.minRating > 0) {
      params.min_rating = filters.minRating
    }
    if (filters.maxFee < 1000) {
      params.max_fee = filters.maxFee
    }
    
    console.log('🔍 使用迭代器API获取医生数据，参数:', params)
    
    const { data } = await request.get('/api/doctors/iterator/', { params })
    if (data && data.code === 0) {
      doctorsData.value = data.data.doctors || []
      
      console.log('🔍 后端返回的医生数据:', doctorsData.value)
      
      // 更新分页信息
      if (data.data.pagination) {
        pagination.total = data.data.pagination.total_items
        pagination.currentPage = data.data.pagination.current_page
      } else {
        pagination.total = doctorsData.value.length
      }
      
      console.log('✅ 医生数据加载成功:', {
        doctors: doctorsData.value.length,
        pagination: data.data.pagination,
        sampleDoctor: doctorsData.value[0] // 显示第一个医生的数据结构
      })
    } else {
      throw new Error(data?.msg || '获取医生列表失败')
    }
  } catch (err) {
    console.error('❌ 获取医生列表失败:', err)
    ElMessage.error(err.message || '获取医生列表失败')
  } finally {
    loading.value = false
  }
}

// 过滤器变化处理
function handleFilterChange() {
  pagination.currentPage = 1
  fetchDoctors() // 重新获取数据
}

// 分页变化处理
function handlePageChange(page) {
  pagination.currentPage = page
  fetchDoctors() // 重新获取数据
}

// 重置过滤条件
function resetFilters() {
  filters.department = null
  filters.minRating = 0
  filters.maxFee = 1000
  filters.specialties = []
  pagination.currentPage = 1
  fetchDoctors()
  ElMessage.success('过滤条件已重置')
}

// 演示不同排序的迭代器使用
function sortDoctorsByRating() {
  if (!doctorsData.value.length) return
  
  // 创建按评分排序的过滤迭代器
  const ratingIterator = IteratorFactory.createFilteredIterator(
    doctorsData.value,
    (doctor) => doctor.rating >= 4.0
  )
  
  const highRatedDoctors = []
  let result = ratingIterator.next()
  while (!result.done) {
    highRatedDoctors.push(result.value.item)
    result = ratingIterator.next()
  }
  
  ElMessage.success(`找到 ${highRatedDoctors.length} 位高评分医生（4.0分以上）`)
}

// 批量处理医生数据示例
function processAllDoctors() {
  if (!doctorIterator) return
  
  doctorIterator.reset()
  const departments = new Set()
  const specialtiesSet = new Set()
  let totalFee = 0
  let count = 0
  
  for (const doctor of doctorIterator) {
    departments.add(doctor.department)
    doctor.specialties?.forEach(specialty => specialtiesSet.add(specialty))
    totalFee += doctor.fee
    count++
  }
  
  const stats = {
    totalDoctors: count,
    departments: Array.from(departments),
    specialties: Array.from(specialtiesSet),
    averageFee: count > 0 ? (totalFee / count).toFixed(2) : 0
  }
  
  console.log('医生统计数据:', stats)
  ElMessage.info(`统计完成：共 ${stats.totalDoctors} 位医生，平均费用 ¥${stats.averageFee}`)
}

onMounted(() => {
  fetchDoctors()
})
</script>

<template>
  <div class="doctor-list-container">
    <div class="header">
      <h2>医生列表 - 迭代器模式演示</h2>
      <div class="actions">
        <el-button @click="sortDoctorsByRating" type="primary">
          查找高评分医生
        </el-button>
        <el-button @click="processAllDoctors" type="info">
          统计医生数据
        </el-button>
        <el-button @click="resetFilters" type="success">
          重置过滤条件
        </el-button>
      </div>
    </div>

    <!-- 过滤器 -->
    <div class="filters">
      <div class="filter-row">
        <div class="filter-item">
          <label>最低评分：</label>
          <el-slider
            v-model="filters.minRating"
            :min="0"
            :max="5"
            :step="0.5"
            show-stops
            @change="handleFilterChange"
          />
        </div>
        <div class="filter-item">
          <label>最高费用：</label>
          <el-slider
            v-model="filters.maxFee"
            :min="0"
            :max="2000"
            :step="50"
            show-input
            @change="handleFilterChange"
          />
        </div>
      </div>
    </div>

    <!-- 调试信息 -->
    <div v-if="!loading" class="debug-info" style="background: #f0f0f0; padding: 10px; margin: 10px 0; border-radius: 4px; font-size: 12px;">
      <p><strong>🐛 调试信息：</strong></p>
      <p>doctorsData.length: {{ doctorsData.length }}</p>
      <p>filteredDoctors.length: {{ filteredDoctors.length }}</p>
      <p>paginatedDoctors.data.length: {{ paginatedDoctors.data.length }}</p>
      <p>loading: {{ loading }}</p>
      <details>
        <summary>查看第一个医生数据</summary>
        <pre>{{ JSON.stringify(paginatedDoctors.data[0], null, 2) }}</pre>
      </details>
    </div>

    <!-- 医生列表 -->
    <div v-loading="loading" class="doctor-grid">
      <div
        v-for="doctor in paginatedDoctors.data"
        :key="doctor.id"
        class="doctor-card"
        :class="{ 'recommended': doctor.is_featured }"
      >
        <div class="doctor-avatar">
          <img :src="doctor.avatar || '/default-avatar.png'" :alt="doctor.name" />
          <span v-if="doctor.is_featured" class="recommended-badge">推荐</span>
        </div>
        
        <div class="doctor-info">
          <h3>{{ doctor.name }}</h3>
          <p class="title">{{ doctor.title }}</p>
          <p class="department">{{ doctor.department?.name || doctor.department }}</p>
          <p class="hospital">{{ doctor.hospital }}</p>
          
          <div class="rating">
            <el-rate
              :model-value="doctor.rating"
              disabled
              show-score
              text-color="#ff9900"
            />
          </div>
          
          <div class="specialties" v-if="doctor.specialty">
            <el-tag size="small" type="info">
              {{ doctor.specialty }}
            </el-tag>
          </div>
          
          <div class="fee">
            <span class="price">¥{{ doctor.consultation_fee }}</span>
            <span class="unit">/次</span>
          </div>
          
          <div class="actions">
            <el-button type="primary" size="small">立即预约</el-button>
            <el-button type="default" size="small">查看详情</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && paginatedDoctors.data.length === 0" class="empty-state">
      <div class="empty-content">
        <div class="empty-icon">🔍</div>
        <h3>暂无符合条件的医生</h3>
        <p>当前过滤条件可能过于严格，请尝试：</p>
        <ul>
          <li>✓ 降低最低评分要求（当前：{{ filters.minRating }}分）</li>
          <li>✓ 提高费用上限（当前：¥{{ filters.maxFee }}）</li>
          <li>✓ 或点击下方按钮重置所有过滤条件</li>
        </ul>
        <el-button @click="resetFilters" type="primary" size="large">
          重置过滤条件
        </el-button>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="paginatedDoctors.data.length > 0" class="pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :total="filteredDoctors.length"
        layout="prev, pager, next, jumper, total"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 迭代器状态信息 -->
    <div class="iterator-stats">
      <el-card>
        <template #header>
          <span>迭代器状态</span>
        </template>
        <p>总医生数：{{ doctorsData.length }}</p>
        <p>过滤后数量：{{ filteredDoctors.length }}</p>
        <p>当前页：{{ pagination.currentPage }} / {{ paginatedDoctors.totalPages || 1 }}</p>
        <p>每页显示：{{ pagination.pageSize }}</p>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.doctor-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filters {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  gap: 40px;
  align-items: center;
}

.filter-item {
  flex: 1;
}

.filter-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.doctor-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.doctor-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 20px;
  background: #fff;
  transition: all 0.3s;
  position: relative;
}

.doctor-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.doctor-card.recommended {
  border-color: #409eff;
  background: linear-gradient(145deg, #fff 0%, #f0f8ff 100%);
}

.doctor-avatar {
  position: relative;
  text-align: center;
  margin-bottom: 15px;
}

.doctor-avatar img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
}

.recommended-badge {
  position: absolute;
  top: -5px;
  right: 20%;
  background: #f56c6c;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
}

.doctor-info h3 {
  margin: 0 0 5px 0;
  color: #303133;
  text-align: center;
}

.title, .department, .hospital {
  color: #606266;
  margin: 5px 0;
  text-align: center;
}

.hospital {
  font-size: 13px;
  color: #909399;
}

.rating {
  margin: 10px 0;
  text-align: center;
}

.specialties {
  margin: 10px 0;
  text-align: center;
}

.specialties .el-tag {
  margin: 2px;
}

.more {
  color: #909399;
  font-size: 12px;
}

.fee {
  text-align: center;
  margin: 15px 0;
}

.price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.unit {
  color: #909399;
  font-size: 12px;
}

.actions {
  text-align: center;
  margin-top: 15px;
}

.actions .el-button {
  margin: 0 5px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-content {
  max-width: 400px;
  margin: 0 auto;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-content h3 {
  color: #303133;
  margin-bottom: 12px;
}

.empty-content p {
  color: #606266;
  margin-bottom: 16px;
}

.empty-content ul {
  text-align: left;
  margin: 16px 0;
  padding-left: 24px;
}

.empty-content li {
  color: #606266;
  margin: 8px 0;
  line-height: 1.5;
}

.empty-content .el-button {
  margin-top: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin: 30px 0;
}

.iterator-stats {
  margin-top: 30px;
}

.iterator-stats .el-card {
  max-width: 300px;
  margin: 0 auto;
}
</style> 